//
//  AppDelegate.m
//  Tospur-text
//
//  Created by Tospur_hewei on 15/9/24.
//  Copyright (c) 2015年 Tospur_hewei. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseViewController.h"
#import "LoginViewController.h"
#import "GuideViewController.h"
#import <AFNetworking.h>
#import "Encryption.h"
#import "NetWork.h"
#define RONGCLOUD_IM_APPKEY @"82hegw5uh4o4x" //请换成您的appkey
@interface AppDelegate ()
{
    BMKMapManager* _mapManager;
}
@property (nonatomic,copy)NSString *sessionid;
@property (nonatomic,copy)NSString *status;
@property (nonatomic, strong) NSString *signature;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //[[NSUserDefaults standardUserDefaults]setValue:@"" forKey:@"loginFlag"];
    //[[NSUserDefaults standardUserDefaults]synchronize];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    //初始化融云SDK
    [[RCIM sharedRCIM] initWithAppKey:RONGCLOUD_IM_APPKEY];
    
#ifdef __IPHONE_8_0
    // 在 iOS 8 下注册苹果推送，申请推送权限。
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge
                                                                                         |UIUserNotificationTypeSound
                                                                                         |UIUserNotificationTypeAlert) categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#else
    // 注册苹果推送，申请推送权限。
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
#endif
    
    self.window.backgroundColor = [UIColor whiteColor];
    
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:@"sqwZtDBKEG6PDER0inesT2Hp" generalDelegate:self];
    
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    
    [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"loginFlag"];
    NSString *loginFlag = [[NSUserDefaults standardUserDefaults]objectForKey:@"loginFlag"];
    if(loginFlag.length == 0){
        GuideViewController *guideVC = [[GuideViewController alloc]init];
        self.window.rootViewController = guideVC;
    }
    else if([loginFlag isEqualToString:@"autoLogin"]){
        self.window.rootViewController = [[UIViewController alloc]init];
        [self LoginAction];
    }
    else if([loginFlag isEqualToString:@"manualLogin"]){
        self.window.rootViewController = [[LoginViewController alloc]init];
    }
    
    //self.window.rootViewController = [[LoginViewController alloc]init];
    
    [self.window makeKeyAndVisible];
    
    UIFont *font = [UIFont systemFontOfSize:19.f];
    NSDictionary *textAttributes = @{
                                     NSFontAttributeName : font,
                                     NSForegroundColorAttributeName : [UIColor whiteColor]
                                     };
    [[UINavigationBar appearance] setTitleTextAttributes:textAttributes];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance]
     setBarTintColor:[UIColor colorWithRed:(1 / 255.0f) green:(149 / 255.0f) blue:(255 / 255.0f) alpha:1]];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(didReceiveMessageNotification:)
     name:RCKitDispatchMessageNotification
     object:nil];
    [[RCIM sharedRCIM] setConnectionStatusDelegate:self];

    
    return YES;
}

/**
 *  将得到的devicetoken 传给融云用于离线状态接收push ，您的app后台要上传推送证书
 *
 *  @param application <#application description#>
 *  @param deviceToken <#deviceToken description#>
 */
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token =
    [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                           withString:@""]
      stringByReplacingOccurrencesOfString:@">"
      withString:@""]
     stringByReplacingOccurrencesOfString:@" "
     withString:@""];
    
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
}


/**
 *  网络状态变化。
 *
 *  @param status 网络状态。
 */
- (void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status {
    if (status == ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT) {
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"提示"
                              message:@"您"
                              @"的帐号在别的设备上登录，您被迫下线！"
                              delegate:nil
                              cancelButtonTitle:@"知道了"
                              otherButtonTitles:nil, nil];
        [alert show];
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        UINavigationController *_navi =
        [[UINavigationController alloc] initWithRootViewController:loginVC];
        self.window.rootViewController = _navi;
    }
}
//自动登录
- (void)LoginAction{


    
    AFHTTPRequestOperationManager *tx = [AFHTTPRequestOperationManager manager];
    //申明返回的结果是json类型
    tx.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    tx.requestSerializer = [AFJSONRequestSerializer serializer];
    // [tx.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
    NSString *urlStr = @"http://172.20.5.46:7001/api/PusherLogin";
    self.signature = [[Encryption shareInstance]sha1];
    NSLog(@"+++++ %@",self.signature);
    NSString *passStr = [[[NSUserDefaults standardUserDefaults]objectForKey:@"passWord"] stringByAppendingString:@"tospur"];
    NSDictionary *dict = @{
                           @"appkey": @"tospur123",
                           @"signature": self.signature,
                           //@"sessionid": @"45785",
                           @"UserName": [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"],
                           @"Password": [[Encryption shareInstance]md5:passStr],
                           };
    [tx POST:urlStr parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"登录返回的数据 === %@",responseObject);
        self.sessionid = [responseObject objectForKey:@"sessionid"];
        self.status = [responseObject objectForKey:@"status"];
        
        
        //[self alertWarning];
        
        if ([self.status isEqualToString:@"200"])
        {
            BaseViewController *baseVC = [[BaseViewController alloc]init];
            [self.window.rootViewController presentViewController:baseVC animated:YES completion:nil];
            [NetWork shareInstance].sessionid = self.sessionid;
        }
        //登录记录
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        
        
    }];

}
- (void)didReceiveMessageNotification:(NSNotification *)notification {
    [UIApplication sharedApplication].applicationIconBadgeNumber =
    [UIApplication sharedApplication].applicationIconBadgeNumber + 1;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
